package leet;

import common.ListNode;

/**
 * @author fance
 * @date 18-5-10 下午3:56
 */
public class ListSum {

    /**
     * 2. 两数相加
     * @param l1
     * @param l2
     * @return
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode tmp1 = l1;
        ListNode tmp2 = l2;
        ListNode head = new ListNode(-1);
        ListNode res = head;
        int carry = 0;
        int cur;
        while (tmp1 != null && tmp2 != null) {
            cur = tmp1.val + tmp2.val + carry;
            if (cur > 9) {
                cur -= 10;
                carry = 1;
            } else { carry = 0;}
            ListNode curNode = new ListNode(cur);
            head.next = curNode;
            head = head.next;
            tmp1 = tmp1.next;
            tmp2 = tmp2.next;
        }
        while (tmp1 != null) {
            cur = tmp1.val + carry;
            if (cur > 9) {
                cur -= 10;
                carry = 1;
            } else { carry = 0;}
            ListNode curNode = new ListNode(cur);
            head.next = curNode;
            head = head.next;
            tmp1 = tmp1.next;
        }
        while (tmp2 != null) {
            cur = tmp2.val + carry;
            if (cur > 9) {
                cur -= 10;
                carry = 1;
            } else { carry = 0;}
            ListNode curNode = new ListNode(cur);
            head.next = curNode;
            head = head.next;
            tmp2 = tmp2.next;
        }

        if (carry == 1) {
            head.next = new ListNode(1);
        }
        return res.next;
    }


    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode head = new ListNode(-1);
        ListNode tmp = head;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                tmp.next = new ListNode(l1.val);
                l1 = l1.next;
            } else {
                tmp.next = new ListNode(l2.val);
                l2 = l2.next;
            }
            tmp = tmp.next;
        }
        while (l1 != null) {
            tmp.next = new ListNode(l1.val);
            tmp = tmp.next;
            l1 = l1.next;
        }
        while (l2 != null) {
            tmp.next = new ListNode(l2.val);
            tmp = tmp.next;
            l2 = l2.next;
        }
        return head.next;
    }
}
